<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        margin: 0;
        padding: 0;
        background-image: url(../../images/grid.png);
      }
      canvas {
        background-color: rgba(255, 0, 0, 0.1);
      }
    </style>
  </head>
  <body>
    <canvas id="tutorial" width="300" height="300px">
      你的浏览器不兼容Canvas,请升级您的浏览器!
    </canvas>

    <script>
      window.onload = function () {
        let canvasEl = document.getElementById('tutorial')
        if (!canvasEl.getContext) {
          return
        }
        let ctx = canvasEl.getContext('2d') // 2d | webgl

        let sun = new Image()
        sun.src = '../images/canvas_sun.png'
        // sun.onload = function() {
        //   // draws
        // }
        let earth = new Image()
        earth.src = '../images/canvas_earth.png'
        let moon = new Image()
        moon.src = '../images/canvas_moon.png'

        requestAnimationFrame(draw)

        /**
         1秒钟会回调 61次
        */
        function draw() {
          ctx.clearRect(0, 0, 300, 300)
          ctx.save()
          drawBg()
          // 2.绘制地球
          drawEarth()
          ctx.restore()
          requestAnimationFrame(draw)
        }

        function drawBg() {
          // 1.绘制背景
          ctx.save()
          ctx.drawImage(sun, 0, 0) // 背景图
          ctx.translate(150, 150) // 移动坐标
          ctx.strokeStyle = 'rgba(0, 153, 255, 0.4)'
          ctx.beginPath() // 绘制轨道
          ctx.arc(0, 0, 105, 0, Math.PI * 2)
          ctx.stroke()
          ctx.restore()
        }

        function drawEarth() {
          let date = new Date()
          let second = date.getSeconds()
          let mill = date.getMilliseconds()
          ctx.save()
          ctx.translate(150, 150)
          ctx.rotate(
            ((Math.PI * 2) / 60) * second + ((Math.PI * 2) / 60 / 1000) * mill
          )
          ctx.translate(105, 0)
          ctx.drawImage(earth, -12, -12)
          // 绘制月球
          drawMoon(second, mill)
          drawEarthMask()
          ctx.restore()
        }

        function drawMoon(second, mill) {
          ctx.save()
          ctx.rotate(
            ((Math.PI * 2) / 10) * second + ((Math.PI * 2) / 10 / 1000) * mill
          )
          ctx.translate(0, 28)
          ctx.drawImage(moon, -3.5, 0)
          ctx.restore()
        }

        function drawEarthMask() {
          ctx.save()
          ctx.fillStyle = 'rgba(0,0,0,0.4)'
          ctx.fillRect(0, -12, 40, 24)
          ctx.restore()
        }
      }
    </script>
  </body>
</html>
